package com.wsx.ones.cloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * Created by wangshuaixin on 17/5/9.
 */
@Service
public class HelloService {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;


    /**
     * HystrixCommand 是断路器上的错误执行方法
     * @param service
     * @return
     */
    @HystrixCommand(fallbackMethod = "getError")
    public String getWords(String service) {
        List<ServiceInstance> services = discoveryClient.getInstances(service);
        if (null != services && services.size() > 0) {
            URI uri = services.get(0).getUri();
            if (null != uri) {
                //注意，此时调用服务，必须使用注册的服务名称，ip是不生效的
                return restTemplate.getForObject("http://"+service+"/hellos/get", String.class);
            }
        }
        return "error";
    }

    public String getError(String service) {
        return service + ": is error";
    }
}
